package cn.jilian.front.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baidu.aip.ocr.AipOcr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;

import cn.jilian.front.domain.DriverLicense;
import cn.jilian.front.service.DriverLicenseService;

@Service
public class DriverLicenseServiceImpl implements DriverLicenseService {
	 @Autowired
	 private AipOcr aipOcr;

	 private ObjectMapper objectMapper = new ObjectMapper();

	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Override
	public DriverLicense handle(byte[] data) {
		 // 传入可选参数调用接口
	    HashMap<String, String> options = new HashMap<String, String>();
	    options.put("detect_direction", "true");
	    JSONObject res = aipOcr.drivingLicense(data, options);
	    return toDriverLicense(res);
	}

	@Override
	public DriverLicense handle(String path) {
		// 传入可选参数调用接口
	    HashMap<String, String> options = new HashMap<String, String>();
	    options.put("detect_direction", "true");
	    JSONObject res = aipOcr.drivingLicense(path, options);
		return toDriverLicense(res);
	}
	
	
	private final static Map<String,String> METAMAP=ImmutableMap.<String, String>builder()
			.put("证号","code")
			.put("姓名","name")
			.put("国籍","nation")
			.put("出生日期","birth")
			.put("性别","gendar")
			.put("住址","address")
			.put("有效期限","usetime")
			.put("有效起始日期","active")
			.put("初次领证日期","receivTime")
			.put("准驾车型","vehicleType")
			.build();
	    
	
	
	private DriverLicense toDriverLicense(JSONObject data) {
		JSONObject d=data.getJSONObject("words_result");
		if(d==null)return null;
		Map<String,String> rs=new HashMap<>(METAMAP.size());
		for(String key:METAMAP.keySet()) {
			if(d.has(key)) {
				JSONObject o=d.getJSONObject(key);
				if(o!=null&&o.has("words")) {
					String v=o.getString("words");
					rs.put(METAMAP.get(key), v);
				}
			}
			
		}
		return objectMapper.convertValue(rs, DriverLicense.class);
		
	}

}
